package web;

import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import mongo.TopicItemDAO;
import tool.DateUtils;
import tool.FileUtils;
import vo.Item;
import vo.Topic;
import vo.TopicItem;
import vo.User;
import vo.UserTopic;
import business.LogService;
import business.TopicService;
import business.UserService;
import business.UserTopicService;
import charts.LineChart;
import charts.PieChart;
import charts.Point;
import charts.SortUtils;

import com.opensymphony.xwork2.Preparable;

import constant.Constant;

@SuppressWarnings("unchecked")
public class ComputeAction implements Preparable {
	private static UserTopicService userTopicService;
	private static UserService userService;
	private static TopicService topicService;
	private LogService logService;

	// 为所有的用户计算home页的统计数据
	public void compHome() {
		try {
			List<User> users = userService.getAllUsers();
			for (User user : users) {
				compHomeEach(user);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 为每一个用户计算home页的统计数据
	public void compHomeEach(User user) {
		try {
			/******** start:计算统计数字 ************/
			ArrayList<String> topicIds = new ArrayList<String>();
			Date today = new Date();
			Date yesterday = DateUtils.str2Date(DateUtils.addDay(today, -1));
			Date last10Day = DateUtils.str2Date(DateUtils.addDay(today, -10));
			int itemSize = 0;
			int todaySize = 0;
			int nonRead = 0;
			// 话题总数
			List<UserTopic> uts = userTopicService.getUserTopicsByUserId(user.getId());
			int topicSize = uts.size();

			// 舆情总数
			for (int i = 0; i < uts.size(); i++) {
				// 我的总舆情数
				String topicNo = String.valueOf(uts.get(i).getTopic().getNo());
				topicIds.add(topicNo);
				int count = TopicItemDAO.getCount(topicNo);
				itemSize += count;

				// 我的24小时舆情个数
				int count24 = TopicItemDAO.getCountByTopicNoTimeRange(topicNo, yesterday, today);
				todaySize += count24;
			}
			System.out.println("我24小时items:" + todaySize);
			// 写home文件
			String homeStr = "";
			homeStr += "topicSize:" + +topicSize + "\n";
			homeStr += "itemSize:" + itemSize + "\n";
			homeStr += "nonRead:" + nonRead + "\n";// TODO:计算时间
			homeStr += "summaryTime:" + "2012-06-10@2012-06-30" + "\n";// TODO:计算时间
			homeStr += "todaySize:" + todaySize + "\n";
			System.out.println("path:" + Constant.root + user.getId() + "/home.txt");
			FileUtils.write(Constant.root + user.getId() + "/home.txt", homeStr);

			// // 计算未10天未读
			// ArrayList<String> nonReads = new ArrayList<String>();
			// List<Log> logs = logService.getByUserIdType(user.getId(),
			// "read");
			// for (Item item : myLast10DayItems) {
			// if (isInLogs(item.getId(), logs))
			// if (!nonReads.contains(item.getId()))// 去掉重复阅读
			// nonReads.add(item.getId());
			// }
			// nonRead = nonReads.size();
			/******** end:计算统计数字 ************/

			/******** start:计算24小时10大 ************/
			List<Item> myYesterdayItems = new ArrayList<Item>();
			// 查询topic在topicIds中的，reply倒序的10个topicItem
			List<TopicItem> myYesterdayTopicItems = TopicItemDAO.getByTopicNosTimeRange(topicIds, yesterday, today);
			System.out.println("myYesterdayTopicItems:" + myYesterdayTopicItems.size());

			for (TopicItem ti : myYesterdayTopicItems) {
				// myYesterdayItems.add(ItemDAO.getById(ti.getItemId()));//TODO:等topicItem中的item都在items中的时候，再开放
				// 等数据好了，删除item，换从item中读取
				Item item = new Item();
				item.setId(ti.getId());
				item.setSource(ti.getSource());
				item.setType(ti.getType());
				item.setPubTime(ti.getPubTime());
				item.setTitle(ti.getFrag().substring(0, 20));// TODO:不知道啥是frag
				myYesterdayItems.add(item);
			}

			// 写yesterday top 10
			String yesterdayTop10 = "";
			for (Item item : myYesterdayItems) {
				yesterdayTop10 += item.getTitle() + "@" + item.getType() + "@" + DateUtils.date2Str(item.getPubTime(), "-") + "#";
			}
			FileUtils.write(Constant.root + user.getId() + "/yesterday_top10.txt", yesterdayTop10);
			/******** end:计算24小时10大 ************/

			/******** start:计算10days 10大 ************/
			List<Item> myLast10DayItems = new ArrayList<Item>();
			// 查询topic在topicIds中的，reply倒序的10个topicItem
			List<TopicItem> myLast10DaysTopicItems = TopicItemDAO.getByTopicNosTimeRange(topicIds, last10Day, today);
			System.out.println("myLast10DaysTopicItems:" + myLast10DaysTopicItems.size());

			for (TopicItem ti : myLast10DaysTopicItems) {
				// myYesterdayItems.add(ItemDAO.getById(ti.getItemId()));//TODO:等topicItem中的item都在items中的时候，再开放
				// 等数据好了，删除item，换从item中读取
				Item item = new Item();
				item.setId(ti.getId());
				item.setSource(ti.getSource());
				item.setType(ti.getType());
				item.setPubTime(ti.getPubTime());
				item.setTitle(ti.getFrag().substring(0, 20));// TODO:不知道啥是frag
				myLast10DayItems.add(item);
			}

			// 写yesterday top 10
			String last10DayTop10 = "";
			for (Item item : myLast10DayItems) {
				last10DayTop10 += item.getTitle() + "@" + item.getType() + "@" + DateUtils.date2Str(item.getPubTime(), "-") + "#";
			}
			FileUtils.write(Constant.root + user.getId() + "/last10Day_top10.txt", last10DayTop10);
			/******** end:10days 10大 ************/
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// public static boolean isInLogs(String itemId, List<Log> logs) {
	// boolean isInLogs = false;
	// for (Log log : logs) {
	// if (log.equals(itemId))
	// isInLogs = true;
	// }
	// return isInLogs;
	// }

	public static void compTrends() {
		try {
			List<User> users = userService.getAllUsers();
			Date today = new Date();
			for (User user : users) {
				// 变量定义
				String last10DayTrends = Constant.root + user.getId() + "/imageTrends.jpg";
				String last10DayTrendsTopic = Constant.root + user.getId() + "/imageTrends_topic.jpg";
				ArrayList<String> topicIds = new ArrayList<String>();
				Hashtable<String, Integer> day_count = new Hashtable<String, Integer>();

				// 统计用户关注的topics
				List<UserTopic> uts = userTopicService.getUserTopicsByUserId(user.getId());
				for (int i = 0; i < uts.size(); i++) {
					String topicNo = String.valueOf(uts.get(i).getTopic().getNo());
					topicIds.add(topicNo);
				}
				System.out.println("topics:" + topicIds.size());
				/********* start:计算10天的舆情趋势 ************/
				for (int day = 0; day < 10; day++) {
					int daySize = 0;
					// 时间段
					Date startDate = DateUtils.str2Date(DateUtils.addDay(today, -day));
					Date endDate = DateUtils.str2Date(DateUtils.addDay(today, -(day - 1)));
					// 时间段内各个topics的舆情个数和
					for (String topicId : topicIds) {
						int count = TopicItemDAO.getCountByTopicNoTimeRange(topicId, startDate, endDate);
						daySize += count;
					}
					System.out.println(DateUtils.date2DateStr(startDate, "-") + "dao" + DateUtils.date2DateStr(endDate, "-") + ":" + daySize);
					day_count.put(String.valueOf(day), daySize);
				}
				ArrayList<Point> points = hash2Points(day_count);
				LineChart.createChart(points, last10DayTrends, "Items Increment Count Trends", 400, 300);
				System.out.println("draw item charts");
				/********* end:计算10天的舆情趋势 ************/

				/********* start:计算10天的舆情趋势 (Topic) ************/
				// 计算最近10天的趋势，单独topic
				ArrayList<ArrayList<Point>> list = new ArrayList<ArrayList<Point>>();
				Hashtable<String, Integer> day_count1 = new Hashtable<String, Integer>();
				Hashtable<String, Integer> day_count2 = new Hashtable<String, Integer>();
				Hashtable<String, Integer> day_count3 = new Hashtable<String, Integer>();

				int daySizes[] = new int[3];// 三个topics
				for (int day = 0; day < 10; day++) {
					// 时间段
					Date startDate = DateUtils.str2Date(DateUtils.addDay(today, -day));
					Date endDate = DateUtils.str2Date(DateUtils.addDay(today, -(day - 1)));
					// 时间段内各个topics的舆情个数和
					System.out.println();

					for (int i = 0; i < topicIds.size(); i++) {
						// 某天的。某topic
						int count = TopicItemDAO.getCountByTopicNoTimeRange(topicIds.get(i), startDate, endDate);
						daySizes[i] = count;// for topic i
						System.out.println(topicIds.get(i) + ":" + count);
						// topic 0
						if (i == 0)
							day_count1.put(String.valueOf(day), daySizes[0]);
						if (i == 1)
							day_count2.put(String.valueOf(day), daySizes[1]);
						if (i == 2)
							day_count3.put(String.valueOf(day), daySizes[2]);
					}
				}

				ArrayList<Point> points1 = hash2Points(day_count1);
				ArrayList<Point> points2 = hash2Points(day_count2);
				ArrayList<Point> points3 = hash2Points(day_count3);
				list.add(points1);
				list.add(points2);
				list.add(points3);
				LineChart.createChartList(list, last10DayTrendsTopic, "Items Increment Count Trends (Each Topic)", 400, 300);
				System.out.println("draw item each topic charts");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static ArrayList<Point> hash2Points(Hashtable<String, Integer> key_value) {
		Map.Entry[] entries = SortUtils.sortedHashtableByKey(key_value, 1);
		ArrayList<Point> points = new ArrayList<Point>();
		for (int i = 0; i < entries.length; i++) {
			points.add(new Point(i, (Integer) entries[i].getValue()));
		}
		return points;
	}

	// 为所有用户计算媒体组成
	public void compSources() {
		try {
			ArrayList<String> sourceIds = new ArrayList<String>();
			sourceIds.add("100003");
			sourceIds.add("100002");
			sourceIds.add("100001");
			sourceIds.add("11");
			sourceIds.add("10");
			List<User> users = userService.getAllUsers();
			Hashtable<String, Integer> sourceId_count = new Hashtable<String, Integer>();
			// 遍历所有用户
			for (User user : users) {
				String imageSources = Constant.root + user.getId() + "/imageSources.jpg";
				List<UserTopic> uts = userTopicService.getUserTopicsByUserId(user.getId());
				// 用户的所有topic
				for (UserTopic ut : uts) {
					String topicId = ut.getTopic().getNo();
					for (String sourceId : sourceIds) {
						int count = TopicItemDAO.getCountByTopicIdSourceId(topicId, sourceId);
						if (sourceId_count.containsKey(sourceId))
							sourceId_count.put(sourceId, sourceId_count.get(sourceId) + count);
						else
							sourceId_count.put(sourceId, count);
					}

				}
				PieChart.createChart(sourceId_count, "Sources", imageSources, 500, 400);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 为所有用户计算媒体组成
	public static void compTrendsByTopics() {
		try {
			Date today = new Date();
			Hashtable<String, Integer> day_count = new Hashtable<String, Integer>();
			System.out.println("1:" + topicService);
			System.out.println("2:" + topicService.getAll());
			List<Topic> topics = topicService.getAll();
			for (Topic topic : topics) {
				String topicId = String.valueOf(topic.getId());
				String last10DayTrends = Constant.root + "topic" + "/" + topicId + "_imageTrends.jpg";
				// 变量定义
				for (int day = 0; day < 10; day++) {
					// 时间段
					Date startDate = DateUtils.str2Date(DateUtils.addDay(today, -day));
					Date endDate = DateUtils.str2Date(DateUtils.addDay(today, -(day - 1)));
					// 时间段内各个topics的舆情个数和
					int daySize = TopicItemDAO.getCountByTopicNoTimeRange(topicId, startDate, endDate);
					System.out.println(DateUtils.date2DateStr(startDate, "-") + "dao" + DateUtils.date2DateStr(endDate, "-") + ":" + daySize);
					day_count.put(String.valueOf(day), daySize);
				}
				ArrayList<Point> points = hash2Points(day_count);
				LineChart.createChart(points, last10DayTrends, "Items Increment Count Trends for Topic " + topicId, 400, 300);
				System.out.println("draw item charts");
				/********* end:计算10天的舆情趋势 ************/

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 为所有用户计算媒体组成
	public void compSourcesByTopics() {
		try {
			ArrayList<String> sourceIds = new ArrayList<String>();
			sourceIds.add("100003");
			sourceIds.add("100002");
			sourceIds.add("100001");
			sourceIds.add("11");
			sourceIds.add("10");
			Hashtable<String, Integer> sourceId_count = new Hashtable<String, Integer>();
			List<Topic> topics = topicService.getAll();
			for (Topic topic : topics) {
				// 用户的所有topic
				String topicId = String.valueOf(topic.getId());
				String imageSources = Constant.root + "topic" + "/"+topicId+"_imageSources.jpg";
				for (String sourceId : sourceIds) {
					int count = TopicItemDAO.getCountByTopicIdSourceId(topicId, sourceId);
					if (sourceId_count.containsKey(sourceId))
						sourceId_count.put(sourceId, sourceId_count.get(sourceId) + count);
					else
						sourceId_count.put(sourceId, count);
				}
				PieChart.createChart(sourceId_count, "Sources", imageSources, 500, 400);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void prepare() throws Exception {
	}

	public void setUserTopicService(UserTopicService userTopicService) {
		ComputeAction.userTopicService = userTopicService;
	}

	public void setUserService(UserService userService) {
		ComputeAction.userService = userService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	public void setTopicService(TopicService topicService) {
		ComputeAction.topicService = topicService;
	}

}